﻿using Dapper;
using MX.Core.ORM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserCenter.Models;

namespace UserCenter.BLL
{
    public static class SmsCodeLogBLL
    {
        public static List<SmsCodeLog> List(string ip, string deviceId, string phone)
        {
            string strSql = @"(SELECT * FROM sms_code_log WHERE IpAddress=@IpAddress ORDER BY CreateTime DESC LIMIT 0,1)
                                UNION ALL 
                                (SELECT * FROM sms_code_log WHERE DeviceId=@DeviceId ORDER BY CreateTime DESC LIMIT 0,1)
                                UNION ALL 
                                (SELECT * FROM sms_code_log WHERE Phone=@Phone ORDER BY CreateTime DESC LIMIT 0,1)";
            using (var conn = DatabaseHelper.Get())
            {
                return conn.Query<SmsCodeLog>(strSql, new { IpAddress = ip, DeviceId = deviceId, Phone = phone }).AsList();
            }
        }

        public static bool Save(SmsCodeLog smsCodeLog)
        {
            string strSql = @"INSERT INTO `sms_code_log` (
                                  `SmsId`,
                                  `Type`,
                                  `Phone`,
                                  `DeviceId`,
                                  `IpAddress`,
                                  `Code`,
                                  `IsValidate`,
                                  `CreateTime`,
                                  `OutSendId`
                                ) 
                                VALUES
                                  (
                                    @SmsId,
                                    @Type,
                                    @Phone,
                                    @DeviceId,
                                    @IpAddress,
                                    @Code,
                                    @IsValidate,
                                    @CreateTime,
                                    @OutSendId
                                  )";
            using (var conn = DatabaseHelper.Get())
            {
                return conn.Execute(strSql, smsCodeLog) > 0;
            }
        }

        public static SmsCodeLog Info(string smsId)
        {
            string strSql = "SELECT * FROM sms_code_log WHERE SmsId=@SmsId ";
            using (var conn = DatabaseHelper.Get())
            {
                return conn.QuerySingleOrDefault<SmsCodeLog>(strSql, new { SmsId = smsId });
            }
        }
    }
}
